#include "Player.h"
#include "Game.h"
#include "ResourceManager.h"
#include "GameObjectFactory.h"
#include <iostream>

static bool playerCreator = TheGameObjectFactory::Instance()->AddType("Player", Player::CreatePlayer);

GameObject* Player::CreatePlayer()
{
	return new Player;
}

Player::Player() :		MeshObject(),
						m_camRotation(Vector3(0,0,0)),
						m_stylusLastX(0),
						m_stylusLastY(0)
{
	m_camDistance = 6.0f;
	m_camHeight = 2.0f;
}

bool Player::Load(File* m_pFile)
{
	MeshObject::Load(m_pFile);
}

void Player::Update(float gameSpeed)
{
	HandleInput();

	MeshObject::Update(gameSpeed);
}

void Player::Draw()
{
	glLoadIdentity();

	// camera values
	glTranslatef(0.0f, -m_camHeight, -m_camDistance);
	glRotatef(m_camRotation.x, 1.0f, 0.0f, 0.0f);

	MeshObject::Draw();

	// translate the scene
	glRotatef(m_camRotation.y, 0.0f, 1.0f, 0.0f);
	glTranslatef(-m_position.x, 0.0f, -m_position.z);
}

void Player::HandleInput()
{
	if(TheGame::Instance()->KeyHeld(KEY_UP))
	{
		m_bMoving = true;
		m_position.x += float(sin(m_camRotation.y / 180 * Math::PI));
		m_position.z -= float(cos(m_camRotation.y / 180 * Math::PI));
		m_position.y -= float(sin(m_camRotation.x / 180 * Math::PI));
	}
	else if(TheGame::Instance()->KeyHeld(KEY_DOWN))
	{
		m_bMoving = true;
		m_position.x -= float(sin(m_camRotation.y / 180 * Math::PI));
		m_position.z += float(cos(m_camRotation.y / 180 * Math::PI));
		m_position.y += float(sin(m_camRotation.x / 180 * Math::PI));
	}
	else if(TheGame::Instance()->KeyHeld(KEY_RIGHT))
	{
		m_bMoving = true;
		m_camRotation.y += 10.0f;

		/*
		float yrotrad;
				yrotrad = (m_camRotation.y / 180 * 3.141592654f);
				m_position.x = float(cos(yrotrad)) * 10.0f;
				m_position.z = float(sin(yrotrad)) * 10.0f;*/
		

	}
	else if(TheGame::Instance()->KeyHeld(KEY_LEFT))
	{
		m_bMoving = true;
		m_camRotation.y -= 10.0f;

		/*
		float yrotrad;
				yrotrad = (m_camRotation.y / 180 * 3.141592654f);
				m_position.x = -float(cos(yrotrad)) * 10.0f;
				m_position.z = -float(sin(yrotrad)) * 10.0f;*/
		

	}
	else if(!TheGame::Instance()->KeyHeld(KEY_RIGHT) || !TheGame::Instance()->KeyHeld(KEY_LEFT) || !TheGame::Instance()->KeyHeld(KEY_UP) || !TheGame::Instance()->KeyHeld(KEY_DOWN))
	{
		m_bMoving = false;
	}

	if(TheGame::Instance()->StylusDown())
	{
		float xdifference = TheGame::Instance()->GetStylusX() - m_stylusLastX;
		float ydifference = TheGame::Instance()->GetStylusY() - m_stylusLastY;

		m_stylusLastX = TheGame::Instance()->GetStylusX();
		m_stylusLastY = TheGame::Instance()->GetStylusY();

		//m_camRotation.x += ydifference / 10.0f; // pad it out a bit
		m_camRotation.y += xdifference / 2.0f;
	}
}